package com.jxt.myjxtmanager.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.widget.ImageView;

import com.jxt.myjxtmanager.utils.DensityUtil;
import com.jxt.myjxtmanager.utils.SystemInfo;

/**
 * Created by wuyexiong on 4/25/15.
 */
public class TabIconView extends ImageView {

	private Paint mPaint;
	private Bitmap mSelectedIcon;
	private Bitmap mNormalIcon;
	private Rect mSelectedRect;
	private Rect mNormalRect;
	private int mSelectedAlpha = 0;

	public TabIconView(Context context) {
		super(context);
	}

	public TabIconView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public TabIconView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}

	/**
	 * 初始化
	 * 
	 * @param totalNum
	 *            tab总数 （计算位置）
	 * @param heightPixels
	 *            tab栏高度（计算位置, 单位dp）
	 * @param normal
	 *            选中前资源id
	 * @param selected
	 *            选中时图片资源id
	 */
	public final void init(int totalNum, int heightPixels, int normal, int selected) {
		DisplayMetrics mDisplayMetrics = SystemInfo.getDeviceDisplayMetrics(getContext());
		this.mNormalIcon = createBitmap(normal);
		this.mSelectedIcon = createBitmap(selected);
		int moddleWidth = mDisplayMetrics.widthPixels / totalNum / 2 - mNormalIcon.getWidth() / 2;
		int moddleHeight = DensityUtil.dip2px(getContext(), heightPixels) / 2 - mNormalIcon.getHeight() / 2;
		this.mNormalRect = new Rect(moddleWidth, moddleHeight, this.mNormalIcon.getWidth() + moddleWidth,
				this.mNormalIcon.getHeight() + moddleHeight);
		this.mSelectedRect = new Rect(moddleWidth, moddleHeight, this.mSelectedIcon.getWidth() + moddleWidth,
				this.mSelectedIcon.getHeight() + moddleHeight);
		;
		this.mPaint = new Paint(1);
	}

	private Bitmap createBitmap(int resId) {
		return BitmapFactory.decodeResource(getResources(), resId);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if (this.mPaint == null) {
			return;
		}
		this.mPaint.setAlpha(255 - this.mSelectedAlpha);
		canvas.drawBitmap(this.mNormalIcon, null, this.mNormalRect, this.mPaint);
		this.mPaint.setAlpha(this.mSelectedAlpha);
		canvas.drawBitmap(this.mSelectedIcon, null, this.mSelectedRect, this.mPaint);
	}

	public final void changeSelectedAlpha(int alpha) {
		this.mSelectedAlpha = alpha;
		invalidate();
	}

	public final void transformPage(float offset) {
		changeSelectedAlpha((int) (255 * (1 - offset)));
	}
}
